import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.concurrent.ArrayBlockingQueue;

/**
 * @author fsyj
 */
public class FileByteProducer extends Thread {
    private ArrayBlockingQueue<IndexedData> queue;
    private File inputFile;

    public final static int BUFFER_SIZE = 1024;

    public FileByteProducer(ArrayBlockingQueue<IndexedData> queue, File inputFile) {
        super("文件读线程");
        this.queue = queue;
        this.inputFile = inputFile;
    }

    @Override
    public void run() {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(inputFile);
            byte[] buffer = new byte[BUFFER_SIZE];
            // 代表字节数组段，读取下标为 no * BUFFER_SIZE
            int no = 0;
            while (fis.read(buffer) != -1) {
                // 将读入的数组放入阻塞队列
                queue.put(new IndexedData(no++, buffer));
                buffer = new byte[BUFFER_SIZE];
            }
            // 文件读完，发送结束标识
            queue.put(new IndexedData(-1, null));
        } catch (IOException | InterruptedException e) {
            // 可以针对异常信息进行日志记录
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
